const { User } = global.model
const R = global.R
const authMiddleware = async (req, res, next) => {
  try {
    const { authorization } = req.headers
    if (!authorization) return res.send(R.errMsg('当前用户未知，请正确姿势操作！'))
    const token = authorization.split(' ').pop()
    // 使用jwt验证token
    const { id } = require('jsonwebtoken').verify(token, process.env.JWT_SECRET)
    const user = await User.findById(id)
    if (!user) return res.send(R.errCode(2, '当前用户不存在，请重试！'))
    req.user = user;
    next();
  } catch (e) {
    res.send(R.errMsg(e.message))
  }
}
module.exports = {
  authMiddleware
}